package engine

import (
	"context"
	cmap "github.com/orcaman/concurrent-map/v2"
)

var engines = cmap.New[*Engine]()
var engineTopCtx, engineTopCancelFunc = context.WithCancel(context.Background())

func GetOrCreateEngine(device string) *Engine {
	e, ok := engines.Get(device)
	if !ok {
		// 不存在，尝试创建一个
		ctx, cancelFunc := context.WithCancel(engineTopCtx)
		e = NewEngine(ctx, cancelFunc, device)
		ok = engines.SetIfAbsent(device, e)
		if !ok {
			// 已经存在了，直接获取
			e, _ = engines.Get(device)
		}
	}

	return e
}

// CloseAllEngines close all engines. be caution
func CloseAllEngines() {
	engineTopCancelFunc()
}
